package com.f.server;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

import com.f.javabean.PushMsg.Push;
import com.google.protobuf.ByteString;

import io.netty.channel.Channel;

public class SendFileThread implements Runnable{

	private Channel channel;
	private String id;
	private String type;
	private String filePath;
	
	public SendFileThread(Channel channel,String id,String type,String filePath){
		this.channel = channel;
		this.id = id;
		this.type = type;
		this.filePath = filePath;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(type.equals("get")){
			hasFile(filePath);
		}else if(type.equals("canrun")){
			sendFile(channel, filePath, id);
		}
		
	}
	
	public void hasFile(String filePath){
		File file = new File(filePath);
		Push.Builder builder = Push.newBuilder();
		builder.setId(id);
		if(!file.exists()){
			builder.setIsstart(false);
			builder.setIsing(false);
			builder.setIsend(true);
			channel.writeAndFlush(builder);
		}else{
			builder.setIsstart(true);
			builder.setIsing(false);
			builder.setIsend(false);
			builder.setFilename(file.getName());
			channel.writeAndFlush(builder);
		}
	}
	
	public void sendFile(Channel channel,String filePath,String id){
		Push.Builder push = Push.newBuilder();
		push.setId(id);
		FileInputStream inputStream = null;
		File file = new File(filePath);
		push.setFilename(file.getName());
		try{
			inputStream = new FileInputStream(file);
			double total = inputStream.available();
			int readNum = 1024;
			byte[] bytes = new byte[readNum];
			DecimalFormat df = new DecimalFormat("######0.00");
			while(inputStream.read(bytes) != -1){
				ByteString byteString = ByteString.copyFrom(bytes);
				push.setFbyte(byteString);
				push.setIsstart(false);
				push.setIsing(true);
				push.setIsend(false);
				double bfb = 1024D/total;
				bfb = Double.parseDouble(df.format(bfb));
				System.out.println(bfb);
				if(bfb>1){
					bfb = 1;
				}
				bfb *= 100;
				bfb = Double.parseDouble(df.format(bfb));
				push.setReadnum(bfb);
				total -= 1024;
				channel.writeAndFlush(push);
				Thread.sleep(1000);
			}
			push.setIsstart(false);
			push.setIsing(false);
			push.setIsend(true);
			push.setId(id);
			channel.writeAndFlush(push);
			System.out.println("end");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(inputStream != null){
					inputStream.close();
					inputStream = null;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
